RxJS
給學好,那就來說說多人訂閱
吧!!
import { Observable } from 'rxjs';
// 被觀察的目標(Observable)
const asyncObs$ = new Observable((subscriber) => {
// 第一步:加入async程式
let count = 0;
const id = setInterval(() => {
count += 1;
subscriber.next(count); // next() 送出資料
}, 1000);
// 第二步: 回傳一個function來代表 "結束訂閱"(參考補充說明1)
return () => {
console.log('結束訂閱!!');
clearInterval(id);
};
});
// 觀察者1(Observer1)
const observer1 = {
next: (data) => console.log(`[Obs1$]:checked ${data}, next!`),
error: (err) => console.log(`[Obs1$]:error is occured: ${err}}`),
complete: () => console.log(`[Obs1$]:complete`),
};
// 觀察者2(Observer2)
const observer2 = {
next: (data) => console.log(`[Obs2$]:checked ${data}, next!`),
error: (err) => console.log(`[Obs2$]:error is occured: ${err}}`),
complete: () => console.log(`[Obs2$]:complete`),
};
// 訂閱
console.log('=== before ===');
const subs1$ = asyncObs$.subscribe(observer1); // observer1開始訂閱
const subs2$ = asyncObs$.subscribe(observer2); // observer2開始訂閱
// 3秒後結束subs1$訂閱
setTimeout(() => {
subs1$.unsubscribe();
}, 3000);
console.log('=== after ===');
// 5秒後結束subs2$訂閱
setTimeout(() => {
subs2$.unsubscribe();
}, 5000);
// === before ===
// === after ===
// [Obs1$]:checked 1, next!
// [Obs2$]:checked 1, next!
// [Obs1$]:checked 2, next!
// [Obs2$]:checked 2, next!
// [Obs1$]:checked 3, next!
// [Obs2$]:checked 3, next!
// 結束訂閱!!
// [Obs2$]:checked 4, next!
// [Obs2$]:checked 5, next!
// 結束訂閱!!
RxJS
來說,你一訂閱我,我就對你負責到底,直到你取消訂閱我(unsubscribe)!// 訂閱
console.log('=== before ===');
const subs1$ = asyncObs$.subscribe(observer1); // observer1開始訂閱
const subs2$ = asyncObs$.subscribe(observer2); // observer2開始訂閱
// 將subs2$加到subs1$之中
subs1$.add(subs2$);
// 3秒後,一個呼叫結束subs1$,subs2$訂閱
setTimeout(() => {
subs1$.unsubscribe(); // 取消訂閱後,就可以把其中相關的訂閱一起取消囉!!
}, 3000);
console.log('=== after ===');
取消訂閱unsubscribe,除了依序取消之外,還可以透過subs1$.add(subs2$)
的方式整合所有的訂閱後,再透過一個指令,一次結束所有的訂閱。
完成了Day4,習慣逐漸養成,超讚!
接下來我們要開始介紹一些RxJS
的operators,來讓各位感受一下RxJS
的威力吧!
小哥哥,這裡好像有個筆誤哦~
// 5秒後結束subs1$訂閱
setTimeout(() => {
subs2$.unsubscribe();
}, 5000);
Hi didilili
感謝妳的用心閱讀,
立馬修改